package org.jeecg.modules.demo.dz.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.demo.dz.constant.DzConstant;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.dz.entity.DzMaterialSkuCart;
import org.jeecg.modules.demo.dz.entity.DzMaterialCart;
import org.jeecg.modules.demo.dz.vo.DzMaterialCartPage;
import org.jeecg.modules.demo.dz.service.IDzMaterialCartService;
import org.jeecg.modules.demo.dz.service.IDzMaterialSkuCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;


 /**
 * @Description: 购物清单
 * @Author: jeecg-boot
 * @Date:   2024-11-26
 * @Version: V1.0
 */
@Api(tags="购物清单")
@RestController
@RequestMapping("/dz/dzMaterialCart")
@Slf4j
public class DzMaterialCartController {
	@Autowired
	private IDzMaterialCartService dzMaterialCartService;
	@Autowired
	private IDzMaterialSkuCartService dzMaterialSkuCartService;
	@Autowired
	private ISysUserService sysUserService;
	
	/**
	 * 分页列表查询
	 *
	 * @param dzMaterialCart
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "购物清单-分页列表查询")
	@ApiOperation(value="购物清单-分页列表查询", notes="购物清单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<DzMaterialCart>> queryPageList(DzMaterialCart dzMaterialCart,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        QueryWrapper<DzMaterialCart> queryWrapper = QueryGenerator.initQueryWrapper(dzMaterialCart, req.getParameterMap());
		queryWrapper.in("status","1","2");
		if(StringUtils.isEmpty(dzMaterialCart.getStatus())){
			queryWrapper.orderByDesc("status = 1");
		}
		Page<DzMaterialCart> page = new Page<DzMaterialCart>(pageNo, pageSize);
		IPage<DzMaterialCart> pageList = dzMaterialCartService.page(page, queryWrapper);
		List<DzMaterialCart> records = pageList.getRecords();
		List<String> createIds = records.stream().map(r -> r.getCreateId()).collect(Collectors.toList());
		List<SysUser> sysUsers = sysUserService.listByIds(createIds);
		Map<String, SysUser> userMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getId, user -> user));
		for (int i = 0; i < records.size(); i++) {
			DzMaterialCart cart = records.get(i);
			SysUser sysUser = userMap.get(cart.getCreateId());
			cart.setPhone(sysUser.getPhone());
			cart.setCreateBy(sysUser.getRealname());
		}
		return Result.OK(pageList);
	}

	 @ApiOperation(value="购物清单-分页列表查询", notes="购物清单-分页列表查询")
	 @GetMapping(value = "/pageMyOrderList")
	 public Result<IPage<DzMaterialCart>> pageMyOrderList(DzMaterialCart dzMaterialCart,
														@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														HttpServletRequest req) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 QueryWrapper<DzMaterialCart> queryWrapper = QueryGenerator.initQueryWrapper(dzMaterialCart, req.getParameterMap());
		 if(StringUtils.isEmpty(dzMaterialCart.getStatus())){
			 queryWrapper.orderByDesc("status = 1");
		 }
		 queryWrapper.eq("create_id",sysUser.getId());
		 queryWrapper.orderByDesc("create_time");
		 Page<DzMaterialCart> page = new Page<DzMaterialCart>(pageNo, pageSize);
		 IPage<DzMaterialCart> pageList = dzMaterialCartService.page(page, queryWrapper);
		 /*pageList.getRecords().stream().forEach(item -> {
			 item.setImage(StringUtils.isNotEmpty(item.getImage()) ? item.getImage()+"?x-oss-process="+DzConstant.w_500 : null);
		 });*/
		 return Result.OK(pageList);
	 }

	 /**
	  *   添加
	  *
	  * @param dzMaterialCartPage
	  * @return
	  */
	 @AutoLog(value = "购物清单-添加")
	 @ApiOperation(value="购物清单-添加", notes="购物清单-添加")
	 @PostMapping(value = "/submitCart")
	 public Result<String> submitCart(@RequestBody DzMaterialCartPage dzMaterialCartPage) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 DzMaterialCart dzMaterialCart = new DzMaterialCart();
		 dzMaterialCart.setSubmitTime(new Date());
		 dzMaterialCart.setStatus("1");
		 BeanUtils.copyProperties(dzMaterialCartPage, dzMaterialCart);
		 dzMaterialCart.setNo(generateNo());
		 dzMaterialCart.setCreateId(sysUser.getId());
		 dzMaterialCart.setCreateBy(sysUser.getUsername());
		 dzMaterialCart.setCreateTime(new Date());
		 dzMaterialCartService.saveMain(dzMaterialCart, dzMaterialCartPage.getDzMaterialSkuCartList());
		 return Result.OK("添加成功！");
	 }

	 public static String generateNo() {
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		 String datePart = sdf.format(new Date());

		 Random random = new Random();
		 int randomPart = random.nextInt(999999); // 生成六位随机数
		 String formatRandomPart = String.format("%06d", randomPart);

		 return datePart + formatRandomPart;
	 }
	
	/**
	 *   添加
	 *
	 * @param dzMaterialCartPage
	 * @return
	 */
	@AutoLog(value = "购物清单-添加")
	@ApiOperation(value="购物清单-添加", notes="购物清单-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DzMaterialCartPage dzMaterialCartPage) {
		DzMaterialCart dzMaterialCart = new DzMaterialCart();
		BeanUtils.copyProperties(dzMaterialCartPage, dzMaterialCart);
		dzMaterialCartService.saveMain(dzMaterialCart, dzMaterialCartPage.getDzMaterialSkuCartList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param dzMaterialCartPage
	 * @return
	 */
	@AutoLog(value = "购物清单-编辑")
	@ApiOperation(value="购物清单-编辑", notes="购物清单-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DzMaterialCartPage dzMaterialCartPage) {
		DzMaterialCart dzMaterialCart = new DzMaterialCart();
		BeanUtils.copyProperties(dzMaterialCartPage, dzMaterialCart);
		DzMaterialCart dzMaterialCartEntity = dzMaterialCartService.getById(dzMaterialCart.getId());
		if(dzMaterialCartEntity==null) {
			return Result.error("未找到对应数据");
		}
		dzMaterialCartService.updateMain(dzMaterialCart, dzMaterialCartPage.getDzMaterialSkuCartList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "购物清单-通过id删除")
	@ApiOperation(value="购物清单-通过id删除", notes="购物清单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		dzMaterialCartService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "购物清单-批量删除")
	@ApiOperation(value="购物清单-批量删除", notes="购物清单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.dzMaterialCartService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "购物清单-通过id查询")
	@ApiOperation(value="购物清单-通过id查询", notes="购物清单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<DzMaterialCart> queryById(@RequestParam(name="id",required=true) String id) {
		DzMaterialCart dzMaterialCart = dzMaterialCartService.getById(id);
		if(dzMaterialCart==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(dzMaterialCart);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "购物清单明细通过主表ID查询")
	@ApiOperation(value="购物清单明细主表ID查询", notes="购物清单明细-通主表ID查询")
	@GetMapping(value = "/queryDzMaterialSkuCartByMainId")
	public Result<List<DzMaterialSkuCart>> queryDzMaterialSkuCartListByMainId(@RequestParam(name="id",required=true) String id) {
		List<DzMaterialSkuCart> dzMaterialSkuCartList = dzMaterialSkuCartService.selectByMainId(id);
		return Result.OK(dzMaterialSkuCartList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param dzMaterialCart
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DzMaterialCart dzMaterialCart) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<DzMaterialCart> queryWrapper = QueryGenerator.initQueryWrapper(dzMaterialCart, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<DzMaterialCart> dzMaterialCartList = dzMaterialCartService.list(queryWrapper);

      // Step.3 组装pageList
      List<DzMaterialCartPage> pageList = new ArrayList<DzMaterialCartPage>();
      for (DzMaterialCart main : dzMaterialCartList) {
          DzMaterialCartPage vo = new DzMaterialCartPage();
          BeanUtils.copyProperties(main, vo);
          List<DzMaterialSkuCart> dzMaterialSkuCartList = dzMaterialSkuCartService.selectByMainId(main.getId());
          vo.setDzMaterialSkuCartList(dzMaterialSkuCartList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "购物清单列表");
      mv.addObject(NormalExcelConstants.CLASS, DzMaterialCartPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("购物清单数据", "导出人:"+sysUser.getRealname(), "购物清单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<DzMaterialCartPage> list = ExcelImportUtil.importExcel(file.getInputStream(), DzMaterialCartPage.class, params);
              for (DzMaterialCartPage page : list) {
                  DzMaterialCart po = new DzMaterialCart();
                  BeanUtils.copyProperties(page, po);
                  dzMaterialCartService.saveMain(po, page.getDzMaterialSkuCartList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
